package restful;

import static java.util.Arrays.*;

import java.util.*;

public class Matchers implements Iterable<String> {

	public static RestfulMethod apply(String uri, RestfulMethod restfulMethod) {
		return restfulMethod.apply(uri);
	}

	public static int brakets(String pattern) {
		return new Brackets(pattern).getCount();
	}

	public static final List<String> matchersOf(RestfulMethod method) {
		String matcher = method.toString();
		return matchersOf(matcher);
	}

	private static List<String> matchersOf(String matcher) {
		List<String> matchers = new LinkedList<String>();
		String regexMatcher = new UriExpression(matcher).toString();
		matchers.add(regexMatcher);
		return matchers;
	}

	static String nameOf(String parameterName) {
		return parameterName.replaceAll(":.*$", "");
	}

	private static String[] parameterNames(String pattern) {
		int brackets = brakets(pattern);

		String[] parameterNames = new String[brackets];
		for (int i = 0; i < brackets; i++) {
			String parameterName = pattern;
			for (int j = 0; j < i + 1; j++) {
				parameterName = parameterName.substring(parameterName.indexOf('{') + 1);
			}
			if (parameterName.indexOf("}") > 0) {
				parameterName = parameterName.substring(0, parameterName.indexOf("}"));
			}
			parameterNames[i] = nameOf(parameterName);
		}

		return parameterNames;
	}

	public static final Map<String, Object> parameters(String pattern) {
		Map<String, Object> parameters = new LinkedHashMap<String, Object>();

		for (String parameterName : asList(parameterNames(pattern))) {
			if (parameterName.endsWith("Id")) {
				parameters.put(parameterName, 0l);
			}
			if (!parameterName.endsWith("Id")) {
				parameters.put(parameterName, "");
			}
		}

		return parameters;
	}

	private List<String> matchers = new LinkedList<String>();

	public Matchers(String pattern) {
		matchers = matchersOf(pattern);
	}

	public Iterator<String> iterator() {
		return matchers.iterator();
	}

	@Override
	public String toString() {
		return matchers.toString();
	}
}
